package com.kun.kunkunmall.search.service.impl;

import cn.hutool.json.JSONUtil;
import com.kun.common.to.es.SkuEsModel;
import com.kun.kunkunmall.search.constant.EsConstant;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSaveServiceImpl implements com.kun.kunkunmall.search.service.ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 保存到es当中

        // 给es中建立索引和映射关系

        // 给索引保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            // 构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String jsonStr = JSONUtil.toJsonStr(skuEsModel);
            indexRequest.source(jsonStr, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        // TODO 批量处理错误
        boolean b = bulk.hasFailures();
        if (b) {
            List<String> collect = Arrays.asList(bulk.getItems()).stream().map(item -> {
                String id = item.getId();
                return id;
            }).collect(Collectors.toList());
            log.error("商品上架错误:{}",collect);
        }
        return b;
    }
}
